package com.fastjars.business.shiro.session;

import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Iterator;

/**
 * ItenDefaultWebSessionManager
 * 自定义WebSessionManager 验证过期Session DefaultSubjectContext.PRINCIPALS_SESSION_KEY为Null就处理
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2017/12/24
 * @version 1.0.0
 */
public class DefaultWebSessionManager extends org.apache.shiro.web.session.mgt.DefaultWebSessionManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWebSessionManager.class);

    @Override
    public void validateSessions() {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Validating all active sessions...");
        }

        int invalidCount = 0;
        Collection<Session> activeSessions = this.getActiveSessions();
        if (activeSessions != null && !activeSessions.isEmpty()) {
            Iterator i$ = activeSessions.iterator();

            while(i$.hasNext()) {
                Session s = (Session)i$.next();

                try {
                    SessionKey key = new DefaultSessionKey(s.getId());
                    if(s instanceof SimpleSession){
                        SimpleSession simpleSession = (SimpleSession) s;
                        if(null == simpleSession.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)){
                            simpleSession.setExpired(true);
                        }
                        this.validate(s, key);
                    }else{
                        this.validate(s, key);
                    }
                } catch (InvalidSessionException var8) {
                    if (LOGGER.isDebugEnabled()) {
                        boolean expired = var8 instanceof ExpiredSessionException;
                        String msg = "Invalidated session with id [" + s.getId() + "]" + (expired ? " (expired)" : " (stopped)");
                        LOGGER.debug(msg);
                    }

                    ++invalidCount;
                }
            }
        }

        if (LOGGER.isInfoEnabled()) {
            String msg = "Finished session validation.";
            if (invalidCount > 0) {
                msg = msg + "  [" + invalidCount + "] sessions were stopped.";
            } else {
                msg = msg + "  No sessions were stopped.";
            }

            LOGGER.info(msg);
        }
    }
}
